#define _CRT_SECURE_NO_WARNINGS

#include "Heap.h"

void HeapInit(HP* hp)
{
	assert(hp);

	hp->a = NULL;
	hp->capacity = 0;
	hp->size = 0;
}

void HeapDestroy(HP* hp)
{
	assert(hp);

	free(hp->a);
	hp->a = NULL;
	hp->capacity = 0;
	hp->size = 0;
}

void HeapCheckCapacity(HP* hp)
{
	assert(hp);

	if (hp->size == hp->capacity)
	{
		int newcapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		HPDataType* ptr = (HPDataType*)realloc(hp->a, sizeof(HPDataType) * newcapacity);
		if (ptr == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}

		hp->a = ptr;
		hp->capacity = newcapacity;
	}
}


void Swap(HPDataType* p1, HPDataType* p2)
{

	HPDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void AdjustUp(HPDataType* a, int child)
{
	
	while (child > 0)
	{
		int parent = (child - 1) / 2;

		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
		}
		else
		{
			break;
		}

		child = parent;
	}
}

void HeapPush(HP* hp, HPDataType x)
{
	assert(hp);

	HeapCheckCapacity(hp);

	hp->a[hp->size] = x;
	hp->size++;

	AdjustUp(hp->a, hp->size - 1);
}

void AdjustDown(HPDataType* a, int n, int parent)
{
	int child = parent * 2 + 1;

	while (child < n)
	{
		if (child + 1 < n && a[child] > a[child + 1])
		{
			child++;
		}

		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);

			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

bool HeapEmpty(HP* hp)
{
	return hp->size == 0;
}

void HeapPop(HP* hp)
{
	assert(hp);
	assert(!HeapEmpty(hp));

	Swap(&hp->a[0], &hp->a[hp->size - 1]);
	hp->size--;

	AdjustDown(hp->a,hp->size,0);
}

HPDataType HeapTop(HP* hp)
{
	assert(hp);
	assert(!HeapEmpty(hp));

	return hp->a[0];
}

int HeapSize(HP* hp)
{
	assert(hp);

	return hp->size;
}